package controller

import (
	"context"
	"fmt"
	"goods_user_srv/data_source"
	"goods_user_srv/models"
	admin_user "goods_user_srv/proto/admin_user"
	)

/*
定义一个和proto中与service同名的结构体
*/
type AdminUser struct {

}

// 重写方法
func (a AdminUser)AdminUserLogin(ctx context.Context, in *admin_user.AdminUserRequest, out *admin_user.AdminUserResponse) error {
	// 具体逻辑
	// 接收参数
	username := in.Username
	password := in.Password

	fmt.Println(username, password)

	// 校验参数
	user := models.AdminUser{}
	data_source.Db.Where(map[string]interface{}{"user_name": username, "password": password}).Find(&user)


	if user.UserName == username && user.Password == password {
		out.UserName = username
		out.Code = 200
		out.Msg = "登陆成功"
	}else {
		out.Msg = "该管理员不存在，请添加管理员"
		out.Code = 500
		out.UserName = username
	}


	return nil
}

func (a AdminUser)FrontUserList(ctx context.Context, in *admin_user.FrontUsersRequest, out *admin_user.FrontUsersResponse) error {
	// 接收参数
	currentPage := in.CurrentPage
	pageSize := in.PageSize

	/*
	current  offset  limit
	   1        0      2
	   2        2      2
	   3        4      2

	offset = limit * (current - 1)
	 */
	offsetNum := pageSize * (currentPage - 1)

	var totalPage int32
	usersCount := []models.User{}
	data_source.Db.Find(&usersCount).Count(&totalPage)


	// 构造数据
	users := []models.User{}
	find := data_source.Db.Limit(pageSize).Offset(offsetNum).Find(&users)

	resultUsers := []*admin_user.FrontUser{}
	for _, v := range users {

		frontUser := admin_user.FrontUser{}
		frontUser.Email = v.Email
		frontUser.Status = int32(v.Status)
		frontUser.Desc = v.Desc
		frontUser.CreateTime = v.CreateTime.Format("2006-01-02 15:04:05")

		resultUsers = append(resultUsers, &frontUser)
	}

	if find.Error != nil {   // 没有找到数据
		out.Code = 500
		out.Msg = "该系统还没有用户"

	}else {
		out.Code = 200
		out.Msg = "OK"
		out.FrontUser = resultUsers
		out.PageSize = pageSize
		out.CurrentPage = currentPage
		out.TotalPage = totalPage
	}


	return nil
}